import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Update {
    public void updateTable() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109_5?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造sql语句
        String sql1 = "update student set id = ? where name = ?";
        String sql2 = "update student set name = ? where id = ?";
        System.out.println("请选择要修改的信息(1.修改学号 2.修改姓名)：");
        int select = scanner.nextInt();
        System.out.println("请输入学号：");
        int id = scanner.nextInt();
        System.out.println("请输入姓名：");
        String name = scanner.next();
        PreparedStatement preparedStatement;
        while(true){
            if(select == 1){
                preparedStatement = connection.prepareStatement(sql1);
                preparedStatement.setInt(1, id);
                preparedStatement.setString(2, name);
                break;
            }else if(select == 2){
                preparedStatement = connection.prepareStatement(sql2);
                preparedStatement.setString(1, name);
                preparedStatement.setInt(2, id);
                break;
            }else{
                System.out.println("选择错误，请重新选择(1.修改学号 2.修改姓名)：");
            }
        }
        //4.发送sql语句
        int n = preparedStatement.executeUpdate();
        System.out.println("n = " + n);
        //5.释放资源
        preparedStatement.close();
        connection.close();
    }
}
